<template>
  <div class="player-list-container">
    <div class="player-list-header">
      <h3>玩家列表</h3>
      <span class="player-count">{{ roomStore.players.length }} 位玩家</span>
    </div>
    
    <!-- 调试按钮：强制标记当前玩家 -->
    <div v-if="roomStore.players.length > 0" class="debug-controls">
      <button @click="forceMarkCurrentPlayer" class="debug-button">
        强制标记当前玩家
      </button>
      <button @click="refreshPlayerList" class="debug-button" style="margin-left: 10px;">
        刷新玩家列表
      </button>
    </div>
    

    
    <ul class="player-list">
      <li v-for="player in sortedPlayers" :key="player.id" 
          :class="['player-card', { 'current-player': player.isCurrent, 'top-player': player.score > 0 && player.score === highestScore }]">
        
        <div class="player-info">
          <!-- 玩家头像，显示玩家颜色和首字母 -->
          <div class="player-avatar" :style="{ backgroundColor: player.color }">{{ getInitial(player.name) }}</div>
          
          <div class="player-details">
            <div class="player-name">{{ player.name }}{{ player.isCurrent ? ' (你)' : '' }}</div>
            <div :class="['player-status', { 'online': player.ready }]">
              {{ player.ready ? '已准备' : '未准备' }}
            </div>
          </div>
        </div>
        
        <!-- 玩家分数 -->
        <div class="player-score">
          <div class="score-value">{{ player.score }}</div>
          <div class="score-label">分数</div>
        </div>
        
        <!-- 玩家区域 -->
        <div class="player-area">
          <div class="area-value">{{ player.area || 0 }}</div>
          <div class="area-label">区域</div>
        </div>
        
        <!-- 准备按钮 - 完全简化条件，直接显示 -->
        <div class="player-controls">
          <div class="player-is-current-badge" v-if="player.isCurrent">
            👑 当前玩家
          </div>
          
          <!-- 完全简化条件，始终显示准备按钮 -->
          <button :class="['ready-button', { 'ready': player.ready, 'current-player-only': !player.isCurrent }]" 
                  :disabled="!player.isCurrent" 
                  @click="toggleReady">
            {{ player.ready ? '取消准备' : '准备' }}
          </button>
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { computed, watch } from 'vue'
import { useRoomStore } from '@/stores/room'

const roomStore = useRoomStore()

// 添加深度监听，监听roomStore中玩家列表的变化
watch(() => roomStore.players, (newPlayers, oldPlayers) => {
  console.log('玩家列表发生变化')
  console.log('新玩家列表:', newPlayers.map(p => ({name: p.name, isCurrent: p.isCurrent})))
  
  // 检查是否有当前玩家
  const hasCurrentPlayer = newPlayers.some(p => p.isCurrent)
  if (!hasCurrentPlayer && newPlayers.length > 0) {
    console.log('玩家列表变化后没有当前玩家，自动设置第一个玩家为当前玩家')
    roomStore.forceSetCurrentPlayer()
  }
}, { deep: true, immediate: true })

// 监听游戏状态变化
watch(() => roomStore.gameStatus, (newStatus, oldStatus) => {
  console.log('游戏状态发生变化:', oldStatus, '->', newStatus)
}, { immediate: true })

// 根据分数排序玩家
const sortedPlayers = computed(() => {
  return [...roomStore.players].sort((a, b) => {
    // 优先按分数降序排列
    if (b.score !== a.score) {
      return b.score - a.score
    }
    // 分数相同时，当前玩家排在前面
    if (a.isCurrent) return -1
    if (b.isCurrent) return 1
    // 其他情况按ID排序（保证稳定性）
    return a.id.localeCompare(b.id)
  })
})

// 获取最高分
const highestScore = computed(() => {
  return Math.max(...roomStore.players.map(p => p.score), 0)
})

// 获取当前玩家
const currentPlayer = computed(() => {
  return roomStore.players.find(player => player.isCurrent)
})

// 获取玩家名称首字母
const getInitial = (name) => {
  return name ? name.charAt(0).toUpperCase() : '?'
}

// 切换准备状态
const toggleReady = async () => {
  const currentPlayer = roomStore.players.find(p => p.isCurrent)
  if (currentPlayer) {
    console.log('切换准备状态:', !currentPlayer.ready)
    console.log('当前玩家信息:', {name: currentPlayer.name, id: currentPlayer.id, roomId: roomStore.roomId})
    
    // 先在本地切换状态，然后调用store方法
    try {
      await roomStore.setPlayerReady(!currentPlayer.ready)
      console.log('准备状态切换成功')
    } catch (error) {
      console.error('准备状态切换失败:', error)
    }
  } else {
    console.log('切换准备状态失败: 找不到当前玩家')
    console.log('玩家列表状态:', roomStore.players.map(p => ({name: p.name, isCurrent: p.isCurrent})))
    
    // 如果没有当前玩家，尝试自动设置第一个玩家为当前玩家
    if (roomStore.players.length > 0) {
      console.log('尝试自动设置第一个玩家为当前玩家')
      roomStore.forceSetCurrentPlayer()
      
      // 由于forceSetCurrentPlayer是同步的，立即再次尝试切换准备状态
      console.log('已设置当前玩家，立即再次尝试切换准备状态')
      const updatedCurrentPlayer = roomStore.players.find(p => p.isCurrent)
      if (updatedCurrentPlayer) {
        try {
          await roomStore.setPlayerReady(!updatedCurrentPlayer.ready)
          console.log('准备状态切换成功')
        } catch (error) {
          console.error('准备状态切换失败:', error)
        }
      }
    }
  }
}

// 调试函数：强制标记第一个玩家为当前玩家
const forceMarkCurrentPlayer = () => {
  console.log('尝试通过roomStore强制标记第一个玩家为当前玩家')
  roomStore.forceSetCurrentPlayer()
  
  // 标记后立即检查玩家状态
  setTimeout(() => {
    const updatedCurrentPlayer = roomStore.players.find(p => p.isCurrent)
    console.log('标记后当前玩家:', updatedCurrentPlayer ? `${updatedCurrentPlayer.name} (ID: ${updatedCurrentPlayer.id})` : '未设置')
    console.log('房间状态:', {
      gameStatus: roomStore.gameStatus,
      playersCount: roomStore.players.length,
      players: roomStore.players.map(p => ({name: p.name, isCurrent: p.isCurrent}))
    })
  }, 100)
}

// 调试函数：刷新玩家列表并强制更新UI
const refreshPlayerList = async () => {
  console.log('尝试刷新玩家列表并强制更新UI')
  await roomStore.refreshPlayerListAndUpdateUI()
}</script>

<style scoped>
.player-list-container {
  position: relative;
  background: var(--surface);
  border-radius: var(--radius-lg);
  padding: 16px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow);
}

.player-list-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5px;
  background: linear-gradient(90deg, var(--primary) 0%, var(--primary-light) 100%);
}



.player-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  margin-left: 10px;
  margin-right: 10px;
}

.player-list-header h3 {
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.player-count {
  font-size: 12px;
  color: var(--text-muted);
}

.player-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex: 1;
  list-style: none;
  padding: 0;
  margin: 0;
}

.player-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 12px 16px;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid rgba(255, 255, 255, 0.05);
    transition: all 0.3s ease;
    position: relative;
    min-height: 60px;
  }

.player-card:hover {
  background: rgba(255, 255, 255, 0.04);
  border-color: rgba(255, 255, 255, 0.1);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.player-card.current-player {
  background: linear-gradient(135deg, rgba(78, 205, 196, 0.1) 0%, rgba(69, 183, 209, 0.1) 100%);
  border-color: rgba(78, 205, 196, 0.3);
}

.player-card.top-player {
  background: linear-gradient(135deg, rgba(255, 230, 109, 0.1) 0%, rgba(255, 107, 107, 0.1) 100%);
  border-color: rgba(255, 230, 109, 0.3);
}

.player-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0; /* 允许flex项收缩 */
}

.player-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.player-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0; /* 允许flex项收缩 */
}

.player-name {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.player-controls {
    display: flex;
    align-items: center;
    flex-direction: column;
    gap: 5px;
    flex: 0 0 auto;
    min-width: 80px;
  }
  
  .player-is-current-badge {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 10px;
    color: #ffd700;
    font-weight: bold;
    background-color: rgba(0, 0, 0, 0.7);
    padding: 2px 5px;
    border-radius: 3px;
  }
  
  .ready-button.current-player-only {
    opacity: 0.3;
    cursor: not-allowed;
  }
  
  .ready-button.current-player-only:hover {
    background-color: var(--primary);
  }

.player-status {
  font-size: 12px;
  color: var(--text-muted);
}

.player-status.online {
  color: var(--success);
}

.player-score {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  flex: 0 0 auto;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: var(--text-primary);
}

.score-label {
  font-size: 10px;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.player-area {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  flex: 0 0 auto;
  margin-left: 8px;
  padding-left: 8px;
  border-left: 1px solid rgba(255, 255, 255, 0.1);
}

.area-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-light);
}

.area-label {
  font-size: 10px;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.player-rank {
  flex: 0 0 auto;
  font-size: 18px;
}

.rank-icon {
  display: inline-block;
}

@media (max-width: 480px) {
  .player-list-container {
    padding: 12px;
  }
  
  .player-list-header h3 {
    font-size: 14px;
  }
  
  .player-card {
    padding: 10px 12px;
  }
  
  .player-avatar {
    width: 32px;
    height: 32px;
    font-size: 12px;
  }
  
  .player-name {
    font-size: 13px;
  }
  
  .score-value {
    font-size: 16px;
  }
}
</style>